package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.object.pojo.vo.OpSuggestionStatVO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.SuggestionService;
import com.tbit.uqbike.service.rpcservice.PurviewService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.PowerLogExportUtil;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.uqbike.webmanager.util.excel.ExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 建议
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Validated
@RestController
@RequestMapping(value = "/suggestion", produces = BaseController.MEDIA_JSON_UTF8)
public class SuggestionController extends BaseController {
    @Autowired
    private SuggestionService suggestionService;
    @Autowired
    private PurviewService purviewService;

    /* 处理 */
    @RequestMapping("/handle")
    public JsonResult handle(Suggestion suggestion, Integer isSend,
                             HttpServletRequest request, Integer type) {
        /* 校验 */
        Assert.notNull(suggestion.getSuggestionId(), "请选择要处理的申诉记录");
        if (StrUtil.isNotEmpty(suggestion.getReply()) && suggestion.getReply().length() > 255) {
            throw new BaseException("回复内容过长");
        }
        suggestion.setHandleTime(new Date());
        suggestion.setState(1);
        if (suggestion.getRemark() == null) {
            suggestion.setRemark("");
        }
        if (null == isSend) {
            isSend = 1;
        }
        /*权限判断*/
        suggestionService.handle(suggestion, isSend, type);
        return JsonResult.ok();
    }

    /**
     * 批量处理
     *
     * @param suggestionIds 意见id集合 英文逗号拼接
     * @param isSend        是否发送短信 1发送 0不发送
     * @param type          处理类型 1客户端意见 2运维端意见
     * @param reply         回复内容
     */
    @RequestMapping("/batchHandle")
    public JsonResult batchHandle(@NotBlank String suggestionIds, @NotNull Integer isSend, @NotNull Integer type,
                                  @Size(max = 255, min = 1, message = "回复内容不能为空或过长") String reply) {
        List<Integer> suggestionIdList = Arrays.stream(suggestionIds.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        suggestionService.batchHandle(suggestionIdList, isSend, reply, type);
        return JsonResult.ok();
    }

    /* 运维处理 */
    @RequestMapping("/handleByAccound")
    public JsonResult handleByAccound(AccountUserSug accountUserSug,
                                      HttpServletRequest request) {
        /* 校验 */
        Assert.notNull(accountUserSug.getSuggestionId(), "{ver.suggestionId.notNull");
        Assert.notNull(accountUserSug.getReply(), "{ver.reply.notNull");
        accountUserSug.setHandleTime(new Date());
        accountUserSug.setState(1);
        if (accountUserSug.getRemark() == null) {
            accountUserSug.setRemark("");
        }
        suggestionService.handleByAccound(accountUserSug);
        return JsonResult.ok();
    }

    /* 更加平台账号id查询 */
    @RequestMapping("/getByAccountId")
    public void getByAccountId(Integer accountId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

//        try {
//            Account account = (Account) session.getAttribute("account");
//            if (!account.getType().equals(UserConstant.USER_AGENT)) {
//                /* 校验 */
//                Assert.notNull(accountId, "平台账户id不能为空");
//            } else {
//                accountId = account.getAccountId();
//            }
//
//            List<Suggestion> suggestions = suggestionService.getByAccountId(accountId);
//
//            map.put(ResponseCode.RET, ResponseCode.SUCC);
//            map.put(ResponseCode.DATA, suggestions);
//        } catch (BaseException e) {
//            ResponseCode.printException(map, e);
//        }
//        OutputUtil.renderText(request, response, map);
    }


    /**
     * 分页查询
     *
     * @param sortName
     * @param accountId
     * @param sign
     * @param rowCount
     * @param pageNO
     * @param state
     * @param startTime
     * @param endTime
     * @param phone
     * @param request
     * @param type
     * @return
     */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(String sortName, String accountIds,
                                @RequestParam(defaultValue = "1") Integer sign,
                                @RequestParam(defaultValue = "10") Integer rowCount,
                                @RequestParam(defaultValue = "1") Integer pageNO,
                                Integer state, Long startTime, Long endTime,
                                String phone,
                                HttpServletRequest request, Integer type, String title) {
        List<Integer> accountIdList = StringUtils.str2List(accountIds, ",", true, true)
                .stream().map(Integer::parseInt).collect(Collectors.toList());
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountIdList = Collections.singletonList(loginInfo.id);
        } else {
            Assert.hasLength(accountIds, "ver.accountIds.notNull");
        }
        if (sortName != null && !"".equals(sortName)) {
            sortName = sortName + (sign == 1 ? " asc" : " desc");
        }

        //权限验证
        if (!purviewService.purviewCheck(loginInfo.id, accountIdList)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }

        /**获取用户意见反馈总数*/
        Integer total = suggestionService.queryCount(state, startTime, endTime, accountIdList, phone, title);
        /**当前返回用户意见反馈行数*/
        List<Suggestion> suggestions = suggestionService.queryPage(state, startTime, endTime, rowCount, pageNO, sortName,
                accountIdList, phone, title);
        /**当前返回运维意见反馈行数*/
        List<AccountSuggestion> accountSuggestions = suggestionService.queryPageByAccount(state, startTime, endTime,
                rowCount, pageNO, sortName, accountIdList, phone, title);
        /**获取用户意见反馈总数*/
        Integer totalByAccount = suggestionService.queryCountByAccount(state, startTime, endTime, accountIdList, phone, title);

        if (type == 1) {
            return JsonResult.ok(accountSuggestions, totalByAccount);
        }
        return JsonResult.ok(suggestions, total);
    }

    /**
     * 意见反馈导出
     *
     * @param accountId
     * @param startTime
     * @param endTime
     * @param state
     * @param request
     * @param response
     * @param type
     * @param phone
     */
    @RequestMapping("/export")
    public void export(String accountIds, Long startTime, Long endTime, Integer state, HttpServletRequest request,
                       HttpServletResponse response, Integer type, String phone, String title) {
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");
        if (StrUtil.isBlank(accountIds)){
            throw new BaseException("区域id为空");
        }
        List<Integer> accountList = Arrays.asList(accountIds.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
        List<SuggestionExport> list = suggestionService.export(accountList, startTime, endTime, state, type, phone, title);
        List<String[]> exportList = PowerLogExportUtil.suggestExport(list);
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel("意见反馈", "意见反馈", null, exportList, response, ExportExcelUtil.EXCEL_FILE_2003);
//        ExportExcelUtils.exportExcel(response, "意见反馈", contents);
    }


    /**
     * 人员统计
     *
     * @param accountId
     * @param rowCount
     * @param pageNO
     * @param state
     * @param startTime
     * @param endTime
     * @param type
     * @return
     */
    @RequestMapping("/getStatPage")
    public Result getStatPage(Integer accountId,
                              @RequestParam(defaultValue = "10") Integer rowCount,
                              @RequestParam(defaultValue = "1") Integer pageNO,
                              Integer state,
                              Long startTime,
                              Long endTime,
                              Integer type) {
        PageInfo<SuggestionStat> pageInfo = suggestionService.getStatPage(accountId, rowCount, pageNO, state, startTime, endTime, type);
        return Result.success(new PageResult<>(pageNO, rowCount, pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList()));
    }


    /**
     * 人员统计导出
     *
     * @return
     */
    @GetMapping("/excelStat")
    public Result excelStat(Integer accountId,
                            Integer state,
                            Long startTime,
                            Long endTime,
                            Integer type) {
        ExcelUtil<SuggestionStat> excelUtil = new ExcelUtil<>(SuggestionStat.class);
        List<SuggestionStat> list = suggestionService.getStatList(accountId, state, startTime, endTime, type);
        return Result.success(excelUtil.exportExcel(list, "人员统计").getData());
    }


    /**
     * 意见反馈统计
     *
     * @param accountId
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping("/getSuggestionStat")
    public Result getSuggestionStat(Integer accountId,
                                    Long startTime,
                                    Long endTime) {
        List<OpSuggestionStatVO> list = suggestionService.getSuggestionStat(accountId, startTime, endTime);
        return Result.success(list);
    }

}
